package org.qfedu.edu.impl;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.qfedu.edu.service.ITokenService;

/**
 * @author xiaobobo
 * @title: TokenService
 * @projectName seckill-fy-2401-parent
 * @description: Token的实现类
 * @date 2024/11/4  14:08
 */
@Slf4j
public class TokenService implements ITokenService {
    /**
     * 配置过期时间
     */
    private Integer expire;

    //加密的key
    private String sign;


    public TokenService(Integer expire,String sign){
          this.expire=expire;
          this.sign=sign;
    }

    //解密算法
    private SignatureAlgorithm signatureAlgorithm=SignatureAlgorithm.HS256;

    //压缩算法
    private CompressionCodec compressionCodec=CompressionCodecs.GZIP;

    @Override
    public String createToken(String id, String username) {
        //这里需要生成token
       String token=Jwts.builder()
                .setId(id)
                .setSubject(username)
                .setExpiration(DateTime.now().plusDays(expire).toDate())
                .signWith(signatureAlgorithm, sign)
                .compressWith(compressionCodec)
                .compact();
        log.info("token是:{}",token);
        return token;
    }

    @Override
    public boolean verify(String token) {
        try {
            Jwts.parser()
                    .setSigningKey(sign)
                    .parseClaimsJws(token);
            return true;
        }catch (Exception err){
            return false;
        }
    }

    @Override
    public Jws<Claims> parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(sign)
                    .parseClaimsJws(token);
        }catch (Exception err){
            log.error("解析token抛出了异常:{}",token);
            return null;
        }
    }

    @Override
    public String refreshToken(String token) {
        //刷新token
        //应该先将数据解析出来 然后从新生成
        Jws<Claims> claimsJws = Jwts.parser()
                .setSigningKey(sign)
                .parseClaimsJws(token);
        String id = claimsJws.getBody().getId();
        String username = claimsJws.getBody().getSubject();
        return createToken(id,username);
    }
}
